package com.myweb;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.reflections.Reflections;

import com.myweb.annotation.Action;
import javax.servlet.annotation.WebListener;

/**
 * Application Lifecycle Listener implementation class MyWebListener
 *
 */
@WebListener
public class MyWebListener implements ServletContextListener {

  /**
   * Default constructor.
   */
  public MyWebListener() {
    // TODO Auto-generated constructor stub
  }

  /**
   * @see ServletContextListener#contextInitialized(ServletContextEvent)
   */
  @Override
  public void contextInitialized(ServletContextEvent arg0) {
    ServletContext c = arg0.getServletContext();

    String path = c.getInitParameter("APP_PACKAGE");
    if (path != null) {

      Map<String, Class<?>> actionMap = new HashMap<String, Class<?>>();
      System.out.println("scan" + path);
      Reflections reflections = new Reflections(path);
      Set<Class<?>> annotated = reflections.getTypesAnnotatedWith(Action.class);
      for (Class<?> class1 : annotated) {
        Action a = class1.getAnnotation(Action.class);
        System.out.println("store" + class1);
        actionMap.put(a.url(), class1);
      }
      c.setAttribute("ACTION_MAP", actionMap);
    }

  }

  /**
   * @see ServletContextListener#contextDestroyed(ServletContextEvent)
   */
  @Override
  public void contextDestroyed(ServletContextEvent arg0) {
    // TODO Auto-generated method stub
  }
}
